﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Athanor.Gui
{
    public class Animation
    {
        const int FPS = 25;

        ITextureGroup textures;
        bool loop = true;
        int actualIndex = 0;
        int accumTime = 0;
        int duration;
        bool running = false;

        public Animation(ITextureGroup group){
            Init(group);
        }

        public Animation(String textureNameRoot, int numTextures)
        {
            Texture2D[] t2ds = new Texture2D[numTextures];
            String tmp;
            for (int i = 0; i < numTextures; ++i)
            {
                tmp = textureNameRoot + String.Format("{0:000}", i+1);
                t2ds[i] = ResourcesManager.GetInstance().GetContentManager().Load<Texture2D>(tmp);
            }
            textures = new TextureArray(t2ds);

            Init(new TextureArray(t2ds));
        }

        public Animation(String _textureName, int _rows, int _cols, int _numFrames)
        {
            Init(new TextureGrid(ResourcesManager.GetInstance().GetContentManager().Load<Texture2D>(_textureName), _rows, _cols, _numFrames));
        }

        private void Init(ITextureGroup group)
        {
            textures = group;
            duration = (1000 / FPS) * textures.getNumFrames();
        }

        public Texture2D getTexture() { return textures.getTexture(actualIndex); }
        public Rectangle getRect() { return textures.getRect(actualIndex); }

        public void update(GameTime gameTime){
            if(running)
            {
                accumTime += gameTime.ElapsedGameTime.Milliseconds;
                if (accumTime > duration && !loop)
                {
                    actualIndex = textures.getNumFrames() - 1;
                    running = false;
                }else{
                    accumTime = accumTime % duration;
                    actualIndex = (int) ((accumTime / (float)duration) * textures.getNumFrames());
                }
            }
        }

        public void startAnim( bool reset ){
            if(reset){
                actualIndex = 0;
                accumTime = 0;
            }
            running = true;
        }
    }
}
